//
//  RegisterViewController.m
//  dangdang
//
//  Created by air on 16/1/21.
//  Copyright © 2016年 luweijie. All rights reserved.
//

#import "RegisterViewController.h"
#import "ModifyPasswordViewController.h"
#import "registerObject.h"
#import "UserProtocolViewController.h"

@interface RegisterViewController ()

@property (nonatomic) BOOL select;
@property (nonatomic, copy) NSString * token;
@property (nonatomic, copy) NSString * phoneString;
@property (nonatomic, copy) NSString * validateCode;

@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _phoneTextField.delegate = self;
    _phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
    _validatedCodeTextField.delegate = self;
    _validatedCodeTextField.keyboardType = UIKeyboardTypeNumberPad;
    
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fingerTapped:)];
    
    [self.view addGestureRecognizer:singleTap];
    
    [self buttonLayout];
}

-(void)fingerTapped:(UITapGestureRecognizer *)gestureRecognizer

{
    [self.view endEditing:YES];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    _token = userObject.accessToken;
    
    if ([_forgetString isEqualToString:@"forget"] || [_forgetString isEqualToString:@"change"]) {
        _coverView.hidden = YES;
        self.title = @"验证";
    }else{
        self.title = @"注册";
    }
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    return [self validateNumber:string];
}

- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

- (void)buttonLayout{
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:_protocolButton.titleLabel.text];
    NSRange strRange = {0,[str length]};
    [str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:strRange];
    [_protocolButton setAttributedTitle:str forState:UIControlStateNormal];
    
   _validatedCodeButton.layer.cornerRadius = 8;
    _nextStepButton.layer.cornerRadius = 8;
}

- (IBAction)registerButtonArray:(UIButton *)sender {
    if (sender.tag == 0) {
        if ([_phoneTextField.text isEqual:nil] || [_phoneTextField.text isEqualToString:@""]) {
            [self alertViewShowWithAlertString:@"手机号不能为空"];
            return;
        }
    
        _phoneString = _phoneTextField.text;
        NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
        [params setObject:_token forKey:@"token"];
        [params setObject:_phoneString forKey:@"phone"];
        
        [self postRequestWithMethodName:@"sms/send_reg_valicode" andParams:params andSender:nil];
    }else if (sender.tag == 1){
        _validatedCodeTextField.text = @"";
    }else if (sender.tag == 2){        
        if ([_phoneTextField.text isEqual:nil] || [_phoneTextField.text isEqualToString:@""]) {
            [self alertViewShowWithAlertString:@"手机号不能为空"];
            return;
        }
        if ([_validatedCodeTextField.text isEqual:nil] || [_validatedCodeTextField.text isEqualToString:@""]) {
            [self alertViewShowWithAlertString:@"验证码不能为空"];
            return;
        }
        if (![_validatedCodeTextField.text isEqualToString:_validateCode]) {
            [self alertViewShowWithAlertString:@"验证码错误"];
            return;
        }
        if (_agreeButton.selected == NO) {
            [self alertViewShowWithAlertString:@"你没有同意用户协议"];
            return;
        }
        _phoneString = _phoneTextField.text;
        NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
        [params setObject:_token forKey:@"token"];
        [params setObject:_phoneString forKey:@"phone"];
        
        [self postRequestWithMethodName:@"user/check_phone" andParams:params andSender:nil];
    }else if (sender.tag == 3){
        if (_select) {
            sender.selected = NO;
            _select = NO;
        }else{
            sender.selected = YES;
            _select = YES;
        }
    }else{
        UserProtocolViewController * userProtocolboardVC = [[UIStoryboard storyboardWithName:@"UserProtocolViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"UserProtocolViewController"];
        [self.navigationController pushViewController:userProtocolboardVC animated:YES];
    }
}

//网络连接返回数据
- (void)requestSuccessedWithResult:(id)result NSURLSessionTask:(NSURLSessionTask *)task sender:(id)sender{
    
    NSString * urlString = [NSString stringWithFormat:@"%@", task.currentRequest.URL];
    
    if ([result isKindOfClass:[NSDictionary class]]) {
        NSString * code = [NSString stringWithFormat:@"%@", [result objectForKey:@"retcode"]];
        if ([urlString isEqualToString:[NSString stringWithFormat:@"%@%@", URLDoman, @"sms/send_reg_valicode"]]){
            if ([code isEqualToString:@"0"]) {
                __block int timeout = 60; //倒计时时间
                dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
                dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
                dispatch_source_set_event_handler(_timer, ^{
                    if(timeout<=0){ //倒计时结束，关闭
                        dispatch_source_cancel(_timer);
                        dispatch_async(dispatch_get_main_queue(), ^{
                            //设置界面的按钮显示 根据自己需求设置
                            [_validatedCodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
                            _validatedCodeButton.userInteractionEnabled = YES;
                        });
                    }else{
                        int seconds = timeout % 61;
                        NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
                        dispatch_async(dispatch_get_main_queue(), ^{
                            //设置界面的按钮显示 根据自己需求设置
                            [UIView beginAnimations:nil context:nil];
                            [UIView setAnimationDuration:1];
                            [_validatedCodeButton setTitle:[NSString stringWithFormat:@"(%@)重新获取",strTime] forState:UIControlStateNormal];
                            [UIView commitAnimations];
                            _validatedCodeButton.userInteractionEnabled = NO;
                        });
                        timeout--;
                    }
                });
                dispatch_resume(_timer);
                
                _validateCode = [NSString stringWithFormat:@"%@", [result objectForKey:@"retmsg"]];
            }else{
                [self alertViewShowWithAlertString:@"手机号码格式不正确"];
            }
        }else{
            if ([code isEqualToString:@"0"]) {
            ModifyPasswordViewController * modifyboardVC = [[UIStoryboard storyboardWithName:@"ModifyPasswordViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"ModifyPasswordViewController"];
                if ([_forgetString isEqualToString:@"change"]) {
                    modifyboardVC.naviTitle = @"修改密码";
                }else{
                    modifyboardVC.naviTitle = @"设置密码";
                }
            userRegister.userPhone = _phoneTextField.text;
                
            [self.navigationController pushViewController:modifyboardVC animated:YES];
                
            }else{
                [self alertViewShowWithAlertString:@"手机号码已注册"];
            }
        }
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
